# -*- coding: utf-8 -*-
from django import forms
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.contrib.auth.views import logout_then_login
from django.core.urlresolvers import reverse
from django.db import transaction
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from main.models import *

def base(request):
    return render_to_response('base.html', RequestContext(request))

def index(request):
    links = [{'link':'aaa', 'display_name':'bbbbd'}]
    links = FriendLink.objects.filter(is_display=True)
    return render_to_response('main/index.html', RequestContext(request, {'links':links}))

def about_us(request):
    return render_to_response('main/about_us.html', RequestContext(request))

def teacher_intro(request):
    return render_to_response('main/teacher_intro.html', RequestContext(request))

def faq(request):
    return render_to_response('main/faq.html', RequestContext(request))

def classes(request):
    return render_to_response('main/classes.html', RequestContext(request))

def news(request):
    return render_to_response('main/news.html', RequestContext(request))

def news_opening_in_china(request):
    return render_to_response('main/news_opening_in_china.html', RequestContext(request))

def news_opening_in_china2(request):
    return render_to_response('main/news_opening_in_china2.html', RequestContext(request))

def hotline(request):
    return render_to_response('main/hotline.html', RequestContext(request))

def contact_us(request):
    return render_to_response('main/contact_us.html', RequestContext(request))

def join_us(request):
    return render_to_response('main/join_us.html', RequestContext(request))
def join_us_1(request):
    return render_to_response('main/join_us_1.html', RequestContext(request))
def join_us_2(request):
    return render_to_response('main/join_us_2.html', RequestContext(request))

FIELDS = (
    'name',
    'sex',
    'birthday',
    'parent_name',
    'parent_relation',
    'company',
    'phone',
    'address',
    'zipcode',
    'email',
    'nursery',
    )

class RegisterForm(forms.Form):
    username = forms.CharField(max_length=30, label='用户名*')
    password1 = forms.CharField(max_length=30, label='密码*', widget=forms.PasswordInput)
    password2 = forms.CharField(max_length=30, label='确认密码*', widget=forms.PasswordInput)
    name = forms.CharField(max_length=20, label='孩子姓名*')
    sex = forms.ChoiceField(label='孩子性别*', widget=forms.Select, choices=SEX, required=False)
    birthday = forms.DateField(label='孩子出生日期*', help_text='<p style="line-height:3px">日期格式：2008-8-8</p>')
    parent_name = forms.CharField(max_length=20, label='家长姓名*')
    parent_relation = forms.ChoiceField(label='与孩子的关系*', widget=forms.Select, choices=RELATION)
    phone = forms.CharField(max_length=20, label='手机号码*')
    email = forms.EmailField(label='Email*')
    company = forms.CharField(max_length=100, required=False, label='工作单位', )
    address = forms.CharField(max_length=100, required=False, label='联络地址')
    zipcode = forms.CharField(max_length=10, required=False, label='邮政编码')
    
    nursery = forms.CharField(max_length=100, required=False, label='在读托儿所名称')

    def clean_username(self):
        username = self.cleaned_data['username'].strip()
        try:
            User.objects.get(username=username)
            raise forms.ValidationError('用户已存在')
        except User.DoesNotExist:
            pass # ignore the error
        return username

    def clean_password2(self):
        pwd1 = self.cleaned_data.get('password1', '')
        pwd2 = self.cleaned_data['password2']
        if pwd1 != pwd2:
            raise forms.ValidationError('密码不一致')
        return self.cleaned_data

    def save(self):
        p = self.cleaned_data
        user = User.objects.create_user(username=p['username'], password=p['password1'], email=p['email'])
        profile = UserProfile()
        for i in FIELDS:
            setattr(profile, i, p[i])
        profile.user = user
        profile.save()

@transaction.commit_on_success
def register(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('register_success'))
    else:
        form = RegisterForm()
    return render_to_response('main/register.html', 
                              RequestContext(request, {'form': form}))

def register_success(request):
    return render_to_response('main/register_success.html', 
                              RequestContext(request))

class PracticeReservationForm(forms.ModelForm):
    class Meta:
        model = PracticeReservation
        exclude = ('processed', )

@transaction.commit_on_success
def reserve(request):
    if request.method == 'POST':
        form = PracticeReservationForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('reserve_success'))
    else:
        form = PracticeReservationForm()
    return render_to_response('main/reserve.html',
                              RequestContext(request, {'form': form}))
def reserve_success(request):
    return render_to_response('main/reserve_success.html', 
                              RequestContext(request))
class LoginForm(forms.Form):
    username = forms.CharField(max_length=30, label='用户名', help_text='<p>如果您没有注册，请先<a href="/register">注册</a></p>')
    password = forms.CharField(widget=forms.PasswordInput, label='密码')

def my_login(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse('index'))

    if request.method == 'POST':
        next = request.POST.get('next')
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(username=username, password=password)
            if user:
                login(request, user)
                if next:
                    return HttpResponseRedirect(next)
                return HttpResponseRedirect(reverse('index'))
    else:
        next = request.GET.get('next', '')
        form = LoginForm()

    return render_to_response('main/login.html',
                              RequestContext(request, {'form': form, 'next': next}))


def my_logout(request):
    return logout_then_login(request, reverse('login'))

@login_required
def bean_test(request):
    return render_to_response('main/bean_test.html', RequestContext(request))
